import React, { useEffect, useState } from 'react';
import type { DatePickerProps, TableProps } from 'antd';
import {
  DatePicker, Select, Space, Input, Button, Flex,
  Form, InputNumber, Popconfirm, Table, Typography
} from 'antd';
import moment from 'moment';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';

// 
interface DataType {
  key: string;
  doctor: string;
  depart: string;
  title: string;
  practice: string;
  flag: string;
  type: string;
  ctime: Date;
  gtime: Date;
}

// const originData = Array.from({ length: 100 }).map<DataType>((_, i) => ({
//   key: i.toString(),
//   doctor: `Edward ${i}`,
//   depart: `London Park no. ${i}`,
//   title: `London Park no. ${i}`,
//   practice: `London Park no. ${i}`,
//   flag: `London Park no. ${i}`,
//   type: `London Park no. ${i}`,
//   ctime: new Date("2024-11-30"),
//   gtime: new Date("2024-11-30"),
// }));

interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
  editing: boolean;
  dataIndex: string;
  title: any;
  inputType: 'number' | 'text';
  record: DataType;
  index: number;
}

const EditableCell: React.FC<React.PropsWithChildren<EditableCellProps>> = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;

  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};
// 
export default function DoctorMGT() {
  // 表格
  const [form] = Form.useForm();
  const [data, setData] = useState<DataType[]>();
  // originData
  const [editingKey, setEditingKey] = useState('');

  // useEffect
  useEffect(() => {
    getdoctor()
  }, [])


  // 获取后端医生列表
  const getdoctor = async () => {
    let { data: { code, msg, data } } = await axios.get('http://127.0.0.1:3005/yjx/ShowDoctor')
    // console.log(data);
    setData(data)

  }


  const isEditing = (record: DataType) => record.key === editingKey;

  const edit = (record: Partial<DataType> & { key: React.Key }) => {
    form.setFieldsValue({ name: '', age: '', address: '', ...record });
    setEditingKey(record.key);
  };

  const cancel = () => {
    setEditingKey('');
  };
  const save = async (key: React.Key) => {
    try {
      const row = (await form.validateFields()) as DataType;

      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        setData(newData);
        setEditingKey('');
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey('');
      }
    } catch (errInfo) {
      // console.log('Validate Failed:', errInfo);
    }
  };

  let navi = useNavigate()

  // 表头列表
  const columns = [
    {
      title: '医生',
      dataIndex: 'name',
      width: '10%',
      editable: true,
    },
    {
      title: '科室',
      dataIndex: 'ke',
      width: '10%',
      editable: true,
    },
    {
      title: '职称',
      dataIndex: 'duties',
      width: '10%',
      editable: true,
    },
    {
      title: '第一执业医院',
      dataIndex: 'yi',
      width: '10%',
      editable: true,
    },
    {
      title: '是否开通账号',
      dataIndex: 'state',
      width: '10%',
      editable: true,
      render: (text: boolean) => {
        return text ? '是' : '否';
      },
    },
    {
      title: '类型',
      dataIndex: 'ty',
      width: '10%',
      editable: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createtime',
      width: '10%',
      editable: true,
      render: (text: Date) => {
        return moment(text).format('YYYY-MM-DD'); // 格式化为 "YYYY-MM-DD"
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updatetime',
      width: '10%',
      editable: true,
      render: (text: Date) => {
        return moment(text).format('YYYY-MM-DD'); // 格式化为 "YYYY-MM-DD"
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_: any, record: DataType) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link onClick={() => save(record.key)} style={{ marginInlineEnd: 8 }}>
              Save
            </Typography.Link>
            <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
              <a>Cancel</a>
            </Popconfirm>
          </span>
        ) : (
          <>
            <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
              Edit
            </Typography.Link>
            <Button type="link" onClick={() => { navi('/DoctorView') }}>View</Button>
            <Button type="link" danger onClick={() => { navi('/DoctorEdit') }}>Delete</Button>
          </>
        );
      },
    },
  ];

  const mergedColumns: TableProps<DataType>['columns'] = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: DataType) => ({
        record,
        inputType: col.dataIndex === 'age' ? 'number' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  // 表格
  const onChange: DatePickerProps['onChange'] = (date, dateString) => {
    // console.log(date, dateString);
  };

  const handleChange = (value: string) => {
    // console.log(`selected ${value}`);
  };
  return (
    <div id='y-doctorMGT'>
      {/* 第一板块 */}
      <div className="above">
        <div style={{ padding: '20px', fontWeight: 'bold', fontSize: '18px', color: '#555578' }}>医生管理</div>
        <div style={{
          display: 'flex',
          justifyContent: 'space-between',
          padding: '0 20px',
          alignItems: 'center',
          height: '100px'
        }}>
          <div style={{
            display: 'flex',
            width: '50%',
            justifyContent: 'space-between',
            alignItems: 'center',
            height: '100px'
          }}>
            <div>
              创建时间&nbsp;<DatePicker onChange={onChange} />
            </div>
            <div>选择职称&nbsp;<Select
              // defaultValue="lucy"
              style={{ width: 120 }}
              placeholder="Select a person"
              onChange={handleChange}
              options={[
                { value: 'jack', label: 'Jack' },
                { value: 'lucy', label: 'Lucy' },
                { value: 'Yiminghe', label: 'yiminghe' },
                { value: 'disabled', label: 'Disabled', disabled: true },
              ]}
            /></div>
            <Input placeholder="Basic usage" style={{ width: 250 }} />
          </div>
          <div>
            <Button type="primary" style={{
              width: '80px',
              color: '#616161',
              background: '#d7d7d7',
              border: '2px solid #d7d7d7'
            }}>查询</Button>
            &nbsp;&nbsp;
            <Button style={{
              width: '80px',
              color: '#a6a6a6',
              background: '#ffffff',
              border: '2px solid #d7d7d7'
            }}>重置</Button>
          </div>
        </div>
      </div>
      {/* 第二板块 */}
      <div className="sequel">
        <div style={{ padding: '20px' }}><Button type="primary">新增医生</Button></div>
        <div style={{ padding: '20px' }}>
          <Form form={form} component={false}>
            <Table<DataType>
              components={{
                body: { cell: EditableCell },
              }}
              bordered
              dataSource={data}
              columns={mergedColumns}
              rowClassName="editable-row"
              pagination={{ onChange: cancel }}
            />
          </Form>
        </div>
      </div>
    </div>
  )
}